package cn.wolfcode.controller;


import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    //给这个方法补充一些信息
    //同时标识这个方法需要角色控制
    //到时候判断的时候也要用到这个注解
    @RequestMapping("/list")
    @RequiresPermissions("role:list")
    public String list(Model model, QueryObject qo){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "role/list";
    }
    @RequiresPermissions("role:input")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        List<Permission> permissions = permissionService.selectList();
        model.addAttribute("permissions",permissions);

        if (id!=null) {
            Role role = roleService.selectOne(id);
            model.addAttribute("role",role);
            List<Permission> ownPermissions=permissionService.queryByRoleId(id);
            model.addAttribute("ownPermissions",ownPermissions);
        }
        return "role/input";
    }
    @RequiresPermissions("role:delete")
    @RequestMapping("/delete")
    public String delete(Long id){

        if (id!=null) {
            roleService.delete(id);
        }
        return "redirect:/role/list";
    }
    @RequestMapping("saveOrUpdate")
    @RequiresPermissions("role:saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] permissionIds){
           roleMapper.insert(role);
        if (permissionIds.length>0&&permissionIds!=null) {
            for (Long permissionId : permissionIds) {
                roleMapper.insertRelation(role.getId(),permissionId);
            }
        }else{
            roleService.update(role,permissionIds);
        }
        return "redirect:/role/list";
    }
}
